package org.example.struct.array2;

/**
 * @author liyishan
 * @date 2024/6/17 11:09
 * @apiNote
 */

public class Test00005LongestPalindrome {

    public String longestPalindrome0(String s) {
        int n = s.length();
        if(n < 2){
            return s;
        }
        int maxLen = 1, begin = 0;
        boolean[][] dp = new  boolean[n][n];
        for(int i = 0; i < n; i++){
            dp[i][i] = true;
        }
        for(int l = 2;l<=n;l++){
            for(int i = 0; i < n; i++){
                int j = i+l-1;
                if(j >= n){
                    break;
                }
                if(s.charAt(j) != s.charAt(i)){
                    dp[i][j] = false;
                }else{
                    if(j-i < 3){
                        dp[i][j] = true;
                    }else{
                        dp[i][j] = dp[i+1][j-1];
                    }
                }
                if(dp[i][j] && j-i+1 > maxLen){
                    maxLen = j-i+1;
                    begin = i;
                }
            }
        }
        return s.substring(begin, begin + maxLen);
    }


    public String longestPalindrome(String s) {
        if (s == null || s.length() < 1) {
            return "";
        }
        int start = 0, end = 0;
        for (int i = 0; i < s.length(); i++) {
            int len1 = expandAroundCenter(s, i, i);
            int len2 = expandAroundCenter(s, i, i + 1);
            int len = Math.max(len1, len2);
            if (len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substring(start, end + 1);
    }

    public int expandAroundCenter(String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        return right - left - 1;
    }
}
